<?php
class MySql{
    protected $link = null;
    protected $options = [
        'table' => '',
        'field' => '',
        'limit' => '',
        'order' => '',
        'where' => ''
    ];
    public function __construct(array $config)
    {
        #进行数据库连接操作
        $this->connect($config);
    }


    protected function connect(array $config){
        $dsn = sprintf("mysql:host=%s;dbname=%s;charset=%s",$config['host'],$config['database'],$config['charset']);
        $pdo = new PDO($dsn,$config['user'],$config['password']);
        $this->link = $pdo;
    }

    //查询操作
    public function query($sql,array $vars = []){
        $sth = $this->link->prepare($sql);
        $sth->execute($vars);
        return $sth->fetchAll();
    }

    //执行操作
    public function execute($sql,array $vars=[]){
        $sth = $this->link->prepare($sql);
        return $sth->execute($vars);
    }


    //链式操作之table
    public function table(string $table){
       $this->options['table'] = $table;
       return $this;
    }

    //链式操作之field
    public function field(...$field){
         $this->options['field'] = '`'.implode('`,`',$field).'`';
         return $this;
    }


    //链式操作之limit
    public function limit(...$limit){
        $this->options['limit'] = " LIMIT ".implode(',',$limit);
        return $this;
    }

    //链式操作之orderBy
    public function orderBy(string $order){
        $this->options['order'] = " ORDER BY ".$order;
        return $this;
    }


    //链式操作之where
    public function where(string $where){
        $this->options['where'] = " WHERE ".$where;
        return $this;
    }

    //链式操作之获取结果集
    public function get(){
        $options = $this->options;
        $sql = "SELECT {$options['field']} FROM {$options['table']} {$options['where']} {$options['order']}{$options['limit']}";
        return $this->query($sql);
    }


    //链式操作之添加
    public function insert(array $vars){
        $value_s = array_values($vars);
        $values = implode(',',array_fill(0,count($vars),'?'));
        $sql = "INSERT INTO {$this->options['table']} (".implode(',',array_keys($vars)).") VALUES ({$values})";
        return $this->execute($sql,$value_s);
    }


    //链式操作之修改
    public function update(array $vars=[]){
        if(empty($this->options['where'])){
            throw new Exception('不能缺少条件');
        }
        $sql = "UPDATE {$this->options['table']} SET ".implode('=?,',array_keys($vars)).'=?'." {$this->options['where']}";
        return $this->execute($sql,array_values($vars));
    }

    //链式操作之删除
    public function delete(){
        if(empty($this->options['where'])){
            throw new Exception('缺少删除条件');
        }
        $sql = "DELETE FROM {$this->options['table']} {$this->options['where']}";
        return $this->execute($sql);
    }




}